//
//  JSFileHandler.m
//  JSReader
//
//  Created by xzoscar on 16/6/19.
//  Copyright © 2016年 hujs. All rights reserved.
//

#import "JSFileHandler.h"
#import "DefineConstant.h"
#import "EpubParseOperation.h"

@implementation JSFileHandler {
    //key-value Pair (@"神雕侠侣":@"var://xxx/xxx/神雕侠侣.epub")
    NSMutableDictionary *_fileDict;
    
    Book *_selectedBook;
    NSString *_selectedBookName;
    
    NSOperationQueue *_parseQueue;
    
}
+ (id)shared {
    static id _s = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _s = [[self alloc] init];
        
    });
    return _s;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
         _fileDict = [NSMutableDictionary dictionary];
        _parseQueue = [[NSOperationQueue alloc] init];
        NSString *str = [kBooksDirPath stringByAppendingPathComponent:@"ReadHistory"];
    }
    return self;
}


- (BOOL)updateBookList {
    BOOL ret = NO;
    
    NSFileManager *manager = [NSFileManager defaultManager];
    
    NSString *bookDirPath = [[NSBundle mainBundle] resourcePath];
    NSDirectoryEnumerator *enumerator = [manager enumeratorAtPath:bookDirPath];
    NSString *file = nil;
    while (file = [enumerator nextObject]) {
        if ([file.pathExtension isEqualToString:@"epub"]) {
//            DLog(@"found book %@", file);
            NSString *filePath = [[NSBundle mainBundle] pathForResource:file ofType:nil];
            NSString *str = [file stringByDeletingPathExtension];
            
            _fileDict[str] = filePath;
            ret = YES;
        }
    }
    return ret;
}

- (NSArray *)allBooks {
    NSArray *arr = [_fileDict allKeys];
    return arr;
}
- (NSDictionary *)allBookNameAndPath {
    return _fileDict;
}
- (BOOL)setSelectedBook:(NSString *)bookName {
    BOOL ret = NO;
    if ([[[JSFileHandler shared] allBooks] containsObject:bookName]) {
//        _selectedBook = book;
//        [[JSFileHandler shared] loadBookWithName:bookName];
        ret = YES;
    }
    return ret;
}
- (Book *)selectedBook {
    return _selectedBook;
}

- (void)setSelectedBookName:(NSString *)name {
    _selectedBookName = name;
}

- (NSString *)selectedBookName {
    return  _selectedBookName;
}

- (void)loadBookWithName:(NSString *)bookName lastReadBook:( Book * _Nullable )lastReadBook completionHandler:(completionHandler)block {
     if (![[[JSFileHandler shared] allBooks] containsObject:bookName]) {
         DLog(@"不包含此书!");
         return;
     }
    _selectedBookName = bookName;
    __weak typeof(self) weakSelf = self;
    EpubParseOperation *op = [[EpubParseOperation alloc] initWithBookName:bookName completion:^(Book *book) {
    
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf->_selectedBook = [book copy];
        //读取到上次阅读过的书籍，则继续从上次结束的地方读取
        if (lastReadBook) {
            strongSelf->_selectedBook.selectedChapter = lastReadBook.selectedChapter;
            strongSelf->_selectedBook.offset = lastReadBook.offset;
        } else {
            strongSelf->_selectedBook.selectedChapter = book.catalogs[0];
            strongSelf->_selectedBook.offset = @0.0;
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (block) {
                block(_selectedBook);
            }
        });
        
    }];
    [_parseQueue addOperation:op];
}

- ( Book * _Nullable )readLastReadBook:(NSString *)bookName{
    if (bookName.length == 0) {
        return nil;
    }
    
    NSArray *arr = [NSKeyedUnarchiver unarchiveObjectWithFile:kReadRecordFile];
    
    Book *book = [arr firstObject];
  
    if (book) {
        DLog(@"缓存中有此书 %@", book.name);
    } else {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:bookName];
        [[NSUserDefaults standardUserDefaults] synchronize];
        DLog(@"缓存中无此书");
    }

    return book;
}

- (void)saveReadRecord:(NSNumber *)offset {
    Book *book = [[JSFileHandler shared] selectedBook];
    NSArray *arr = @[book];
    
    [NSKeyedArchiver archiveRootObject:arr toFile:kReadRecordFile];

    [[NSUserDefaults standardUserDefaults] setObject:book.name forKey:kBookName];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)removeReadRecord {
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kBookName];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
@end


